package de.fuberlin.inf.alp3.ue08;

import java.io.File;
import java.io.FileNotFoundException;

public class Where {

	public static void main(String[] args) {
		try {
			//if dir is "~" - concerning to the example - we convert it to "/"			
			SortedSet<String> ss = search(args[0].replace("~", "/"), args[1], Integer.parseInt(args[2]));
			
			System.out.println("Results:");
			for(int i = 0; i < ss.length(); i++) {
				System.out.println(ss.get(i));
			}
			
		} catch(FileNotFoundException e) {
			System.err.println("The Directory is invalid or the File could not have been found");
		} catch(IllegalArgumentException e) {
			System.err.println("The entererd depth is negative");
		} catch(NullPointerException e) {
			System.err.println("The entered dir or name are not valid");
		}		
	}
	
	private static SortedSet<String> search(String dir, String name, int depth)
		throws FileNotFoundException, IllegalArgumentException, NullPointerException {
		
		if(depth < 0)
			throw new IllegalArgumentException();
		if(dir == null || name == null)
			throw new NullPointerException();
		
		SortedSet<String> ss = new Search<String>(dir, name, depth).make();
		if(ss.isEmpty())
			throw new FileNotFoundException();
		
		return ss;
	}

}
class Search<E> {
	private String dir;
	private String name;
	private int depth;
	private SortedSet<String> ss = new SortedSet<String>();
	
	public Search(String dir, String name, int depth) {
		this.dir = dir;
		this.name = name;
		this.depth = depth;
	}
	
	public SortedSet<String> make() {		
		return search(this.dir, this.depth);
	}
	
	//depth d == 0 --> search in the main dir
	//depth d >= 1 --> search in d subfolders
	private SortedSet<String> search(String direc, int d) {
		if(d >= 0) {	
			File file = new File(direc);
			String[] list = file.list();
			
			for(String results : list) {
				if(nameIsLikeResult(results))
					ss.add(direc + "/" + results);
			}	
			
			//recursive call, one dir deeper and depth-1
			File[] files = file.listFiles();
			for(File f : files) {
				if(f.isDirectory())
					search(direc + "/" + f.getName(), d-1);
			}
		}
		return ss;
	}
	
	private boolean nameIsLikeResult(String results) {
		if(results.toLowerCase().contains(name.toLowerCase()))
			return true;
		else
			return false;
	}
}